package org.jash.shop2112.cart

import android.graphics.Paint
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import org.jash.shop2112.BR
import org.jash.shop2112.R
import org.jash.shop2112.databinding.FragmentCartBinding
import org.jash.shop2112.entity.Cart
import org.jash.shop2112.entity.CartItem
import org.jash.shop2112.mvvm.BaseFragment
import org.jash.shop2112.utils.CommonAdapter
import org.jash.shop2112.utils.Event
import org.jash.shop2112.utils.MyItemAnimator
import org.jash.shop2112.utils.bus

@Route(path = "/shop/cart")
class CartFragment : BaseFragment<FragmentCartBinding, CartViewModel>() {
    private val cart by lazy { Cart() }
    private val adapter by lazy { CommonAdapter<CartItem>({R.layout.cart_item to BR.item}, cart.data) }
    override fun initData() {
        viewModel.cartsLiveData.observe(viewLifecycleOwner) {
            adapter += it
            bus.postValue("updateCartSize" to it.size)
        }
        viewModel.deleteLiveData.observe(viewLifecycleOwner) { id ->
            adapter.removeIf { it.id == id }
            bus.postValue("updateCartSize" to cart.data.size)
            cart.notifyPropertyChanged(BR.all)
        }
        viewModel.loadCarts()
    }
    override fun initView() {
        binding.recycler.adapter = adapter
        binding.recycler.itemAnimator = MyItemAnimator()
        binding.cart = cart
        binding.checkedAll.addOnCheckedStateChangedListener { _, i ->
            cart.all = i
        }
        binding.price.paint.flags = Paint.STRIKE_THRU_TEXT_FLAG or binding.price.paint.flags
        binding.buy.setOnClickListener {
            val items = cart.data.filter { it.checked }
            if (items.isNotEmpty()) {
                ARouter.getInstance()
                    .build("/shop/pay")
                    .withString("info", items.joinToString ("\n"){ "${it.goods_desc} x ${it.count}" })
                    .withFloat("price", cart.coupon)
                    .navigation()
            } else {
                Toast.makeText(requireContext(), "至少有一个购买物品", Toast.LENGTH_SHORT).show()
            }
            
        }
    }
    @Event("删除购物车")
    fun delete(item: CartItem) {
        MaterialAlertDialogBuilder(requireContext())
            .setTitle("确认删除")
            .setMessage("确认删除 ${item.goods_desc} 吗?")
            .setNegativeButton("否", null)
            .setPositiveButton("是") { _, _ ->
                viewModel.deleteCart(item.id)
            }.show()
    }
    @Event("refreshAll")
    fun refresh(str:String) {
        cart.notifyPropertyChanged(BR.all)
    }
}